package com.ericsson.enap.modules.kpi.service.impl;

import com.ericsson.common.util.DateUtils;
import com.ericsson.enap.modules.kpi.entity.EnipMeasInfo;
import com.ericsson.enap.modules.kpi.entity.EnipMeasValue;
import com.ericsson.enap.modules.kpi.entity.ImsFiveKpi;
import com.ericsson.enap.modules.kpi.service.EnipKpiFileProcess;
import com.jcraft.enipjsch.ChannelExec;
import com.jcraft.enipjsch.JSch;
import com.jcraft.enipjsch.Session;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.*;

/**
 * PCFUDR类型网元五分钟指标处理
 */
@Component
public class KpiFileProcessPCFUDRFIVEImpl implements EnipKpiFileProcess {

    public List<File> download(ImsFiveKpi imsFiveKpi, String localDir, Logger log, Date date, int delay) {
        return null;
    }

    @Override
    public Map<String, List<File>> download(ImsFiveKpi imsFiveKpi, String localDir, Logger log, Date date) {
        log.info("===================================================  start KpiFileProcessPCFUDRFIVEImpl Files");
        String beginTime = DateUtils.getStatisTime(0, date, "yyyyMMdd_HHmm");
        TreeMap<String, List<File>> fileMap = new TreeMap<>();
        List<File> fileList;
        Session session = null;
        ChannelExec channelExec = null;
        ChannelExec channelExecErrorLog = null;
        BufferedReader input = null;
        BufferedReader inputErrorLog = null;
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(imsFiveKpi.getUsername(), imsFiveKpi.getIp4(), 22);
            session.setConfig("kex", "diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group-exchange-sha256");
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(imsFiveKpi.getPassword());
            session.connect();
            channelExec = (ChannelExec) session.openChannel("exec");
            channelExec.setCommand("bash /home/jtckpt/5gcsts.sh --kpi -p 10 -i 5 ");
            //channelExec.setCommand("cat /opt/yanghai/pcfudr/1.txt ");
            channelExec.setInputStream(null);
            input = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            channelExec.connect();
            StringBuilder sb = new StringBuilder();
            String line;
            String last = "1";
            int spaceCount = 0;
            while ((line = input.readLine()) != null) {
                if (spaceCount != 0) {
                    if (!last.equals("") || !line.equals("")) {
                        sb.append(line).append("\n");
                    }
                    last = line;
                }
                if (line.contains("get KPI:")) {
                    spaceCount = spaceCount + 1;
                }
            }
            fileList = new ArrayList<>();
            File pcfUdrFile = new File(localDir + File.separator + beginTime + ".log");
            FileUtils.write(pcfUdrFile, sb.toString(), "utf-8", false);
            fileList.add(pcfUdrFile);

            //--getError----
            channelExecErrorLog = (ChannelExec) session.openChannel("exec");
            channelExecErrorLog.setCommand("bash /home/jtckpt/5gcsts.sh --error -p 10 -i 5 ");
            //channelExecErrorLog.setCommand("cat /opt/yanghai/pcfudr/pcfudr.txt ");
            inputErrorLog = new BufferedReader(new InputStreamReader(channelExecErrorLog.getInputStream()));
            channelExecErrorLog.setInputStream(null);
            StringBuilder sbErrorLog = new StringBuilder();
            channelExecErrorLog.connect();
            String lineErrorLog;
            String lastErrorLog = "1";
            int spaceCountErrorlog = 0;
            while ((lineErrorLog = inputErrorLog.readLine()) != null) {
                if (spaceCountErrorlog != 0) {
                    if (!lastErrorLog.equals("") || !lineErrorLog.equals("")) {
                        sbErrorLog.append(lineErrorLog).append("\n");
                    }
                    lastErrorLog = lineErrorLog;
                }
                if (lineErrorLog.contains("get Error:")) {
                    spaceCountErrorlog = spaceCountErrorlog + 1;
                }
            }

            File pcfUdrErrorFile = new File(localDir + File.separator + beginTime + "_error.log");
            FileUtils.write(pcfUdrErrorFile, sbErrorLog.toString(), "utf-8", false);
            fileList.add(pcfUdrErrorFile);

            fileMap.put(beginTime, fileList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("PCFUDR:" + e.getMessage(), e);
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                log.error("input:" + e.getMessage(), e);
                e.printStackTrace();
            }
            try {
                inputErrorLog.close();
            } catch (IOException e) {
                log.error("input:" + e.getMessage(), e);
                e.printStackTrace();
            }

            if (channelExec != null && !channelExec.isClosed()) {
                channelExec.disconnect();
            }
            if (channelExecErrorLog != null && !channelExecErrorLog.isClosed()) {
                channelExecErrorLog.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
        return fileMap;
    }

    /**
     * 解析文件
     *
     * @param files
     * @param log
     * @return
     */
    public List<EnipMeasInfo> analysis(List<File> files, Logger log) {
        List<EnipMeasInfo> meansInfoList = new ArrayList<>();
        for (File file : files) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(file));
                String tempStr;
                int spaceCount = 0;
                EnipMeasInfo mi = new EnipMeasInfo();
                Map<String, String> mtMap = new HashMap<>();
                Map<String, String> rMap = new HashMap<>();
                EnipMeasValue measValue = new EnipMeasValue();
                String beginTime = "";
                String lastStr = "";
                if (!file.getName().contains("error")) {//读取普通格式kpi文件
                    while ((tempStr = reader.readLine()) != null) {
                        if (tempStr.contains(":~>")) {
                            break;
                        }
                        if (spaceCount % 2 == 1 && !tempStr.equals("")) {//key
                            mtMap.put(tempStr.split(" ")[1], String.valueOf(mtMap.size() + 1));
                        }
                        if (spaceCount != 0 && spaceCount % 2 == 0 && !lastStr.equals("") && tempStr.equals("")) {
                            String[] valueStr = lastStr.replaceAll(" +", " ").split(" ");
                            beginTime = valueStr[0].replace("_", " ").substring(0, 19);
                            for (String v : valueStr) {
                                if (!v.contains("-") && !v.contains("%"))
                                    rMap.put(String.valueOf(rMap.size() + 1), v);
                            }
                        }
                        if (tempStr.trim().equals("")) {
                            spaceCount = spaceCount + 1;
                        }
                        lastStr = tempStr;
                    }
                } else {//读取error格式文件
                    while ((tempStr = reader.readLine()) != null) {
                        if (tempStr.contains(":~>")) {
                            break;
                        }
                        if (spaceCount % 2 == 1 && !tempStr.equals("")) {//key
                            mtMap.put(tempStr.substring(tempStr.indexOf(" ")).trim(), String.valueOf(mtMap.size() + 1));
                        }
                        if (spaceCount != 0 && spaceCount % 2 == 0 && !lastStr.equals("") && tempStr.equals("")) {
                            String[] valueStr = lastStr.replaceAll(" +", " ").split(" ");
                            beginTime = valueStr[0].replace("_", " ").substring(0, 19);
                            for (String v : valueStr) {
                                if (!v.contains("-") && !v.contains("%"))
                                    rMap.put(String.valueOf(rMap.size() + 1), v);
                            }
                        }
                        if (tempStr.trim().equals("")) {
                            spaceCount = spaceCount + 1;
                        }
                        lastStr = tempStr;
                    }
                }
                measValue.setMeasObjLdn("measObjLdn");
                measValue.setRMap(rMap);
                Map<String, EnipMeasValue> mvMap = mi.getMeasValueMap();
                mvMap.put("measObjLdn", measValue);
                mi.setMeasTypeMap(mtMap);
                mi.setBeginTime(beginTime);
                meansInfoList.add(mi);
            } catch (IOException e) {
                log.error("KpiFileProcessUDMUDRFIVEImpl" + e.getMessage());
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e1) {
                        log.error("KpiFileProcessUDMUDRFIVEImpl" + e1.getMessage());
                    }
                }
            }
        }
        return meansInfoList;
    }

    @Override
    public File download(ImsFiveKpi imsFiveKpi, String localDir, Logger log) {
        return null;
    }

    @Override
    public boolean needUncompress() {
        return false;
    }

    @Override
    public NetType getNetType() {
        return NetType.pcfudr;
    }
}
